package cn.lzy.demo.okhttp;

import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Description  OkHttp 普通请求方法
 * @Author lzy
 * @Date 2023/12/1 15:23
 * @Version
 **/
public class OkHttpDemo {

    public static void main(String[] args) throws InterruptedException {

        // 通过建造者模式去创建 OkHttpClient 对象
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();
        // 创建一个请求
        Request req = new Request.Builder()
                .get()
                .url("https://www.baidu.com")
                .build();
        // 创建一个呼叫对象
        Call call = client.newCall(req);

        // 创建一个计数器
        CountDownLatch countDownLatch = new CountDownLatch(1);
        // 执行网络请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // 计数器减一
                countDownLatch.countDown();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("response.body().string() = " + response.body().string());
                // 计数器减一
                countDownLatch.countDown();
            }
        });

        // 会判断计数器是否为 0，如果为 0，才会继续执行后续的代码，否则就暂停在这里
        countDownLatch.await();
    }
}
